using B.S.RbacData.Domain.Traceabilitys;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Read.API.Applications.Commands.Traceabilitys.DeepProcessings;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.RbacData.Read.API.Applications.CommandHandlters.Traceabilitys.DeepProcessings
{
    /// <summary>
    /// 获取供应商信息命令处理器
    /// </summary>
    public class GetSupplierCommandHandlter : IRequestHandler<GetSupplierCommand, ApiResult<List<SupplierModel>>>
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        private readonly DataDbcontext dataDbcontext;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<GetSupplierCommandHandlter> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dataDbcontext">数据库上下文</param>
        /// <param name="logger">日志</param>
        public GetSupplierCommandHandlter(DataDbcontext dataDbcontext, ILogger<GetSupplierCommandHandlter> logger)
        {
            this.dataDbcontext = dataDbcontext;
            this.logger = logger;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回任务</returns>
        public async Task<ApiResult<List<SupplierModel>>> Handle(GetSupplierCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 根据溯源编号获取供应商信息，并按时间倒序排序
                var supplierList = await dataDbcontext.Suppliers
                    .Where(p => p.ProductId == request.ProductId&&p.TypeName==request.TypeName)
                    .OrderByDescending(p => p.CreaTime)
                    .ToListAsync();

                return new ApiResult<List<SupplierModel>>
                {
                    code = ResultEnumCode.Ok,
                    message = "获取供应商信息成功",
                    data = supplierList
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取供应商信息异常");
                return new ApiResult<List<SupplierModel>>
                {
                    code = ResultEnumCode.fails,
                    message = "获取供应商信息失败: " + ex.Message
                };
            }
        }
    }
} 